class TrustDragManager {
  constructor() {
    this.dragHistory = []
    this.combinationHistory = []
    this.combinationRules = []
    this.activeDrags = new Map()
    this.dropZones = new Map()
    
    this.initializeDefaultRules()
  }
  
  // 初始化默认组合规则
  initializeDefaultRules() {
    this.combinationRules = [
      // 信任值组合规则
      {
        id: 'trust_boost',
        name: '信任提升',
        icon: '📈',
        description: '组合两张卡牌提升信任值',
        matches: (card1, card2) => {
          return card1.trustValue > 0 && card2.trustValue > 0
        },
        apply: (card1, card2) => {
          const combinedTrust = Math.min(100, card1.trustValue + card2.trustValue)
          return {
            type: 'trust_boost',
            value: combinedTrust,
            description: `信任值提升至 ${combinedTrust}`
          }
        }
      },
      
      // 属性组合规则
      {
        id: 'attribute_synergy',
        name: '属性协同',
        icon: '⚡',
        description: '相同属性卡牌组合产生协同效果',
        matches: (card1, card2) => {
          if (!card1.attributes || !card2.attributes) return false
          return Object.keys(card1.attributes).some(key => 
            card2.attributes[key] && card1.attributes[key] > 0 && card2.attributes[key] > 0
          )
        },
        apply: (card1, card2) => {
          const synergies = []
          Object.keys(card1.attributes).forEach(key => {
            if (card2.attributes[key] && card1.attributes[key] > 0 && card2.attributes[key] > 0) {
              synergies.push({
                attribute: key,
                value: card1.attributes[key] + card2.attributes[key],
                description: `${key} 属性协同增强`
              })
            }
          })
          return {
            type: 'attribute_synergy',
            synergies: synergies,
            description: `属性协同效果激活`
          }
        }
      },
      
      // 特殊组合规则
      {
        id: 'perfect_match',
        name: '完美匹配',
        icon: '💎',
        description: '两张高信任值卡牌完美组合',
        matches: (card1, card2) => {
          return card1.trustValue >= 80 && card2.trustValue >= 80
        },
        apply: (card1, card2) => {
          return {
            type: 'perfect_match',
            value: 100,
            description: '完美匹配！信任值达到最大值'
          }
        }
      },
      
      // 互补组合规则
      {
        id: 'complementary',
        name: '互补组合',
        icon: '🤝',
        description: '不同属性卡牌互补组合',
        matches: (card1, card2) => {
          if (!card1.attributes || !card2.attributes) return false
          const card1Keys = Object.keys(card1.attributes)
          const card2Keys = Object.keys(card2.attributes)
          return card1Keys.some(key => !card2Keys.includes(key)) && 
                 card2Keys.some(key => !card1Keys.includes(key))
        },
        apply: (card1, card2) => {
          const combinedAttributes = { ...card1.attributes, ...card2.attributes }
          return {
            type: 'complementary',
            attributes: combinedAttributes,
            description: '互补组合成功，获得新属性'
          }
        }
      }
    ]
  }
  
  // 记录拖拽开始
  recordDragStart(cardId, position) {
    const dragSession = {
      id: Date.now(),
      cardId: cardId,
      startPosition: position,
      startTime: Date.now(),
      status: 'dragging'
    }
    
    this.activeDrags.set(cardId, dragSession)
    this.dragHistory.push(dragSession)
    
    console.log('Drag started:', dragSession)
  }
  
  // 记录拖拽结束
  recordDragEnd(cardId, success) {
    const dragSession = this.activeDrags.get(cardId)
    if (dragSession) {
      dragSession.endTime = Date.now()
      dragSession.duration = dragSession.endTime - dragSession.startTime
      dragSession.status = success ? 'completed' : 'cancelled'
      dragSession.success = success
      
      this.activeDrags.delete(cardId)
      
      console.log('Drag ended:', dragSession)
    }
  }
  
  // 记录组合
  recordCombination(card1Id, card2Id, effects) {
    const combination = {
      id: Date.now(),
      card1Id: card1Id,
      card2Id: card2Id,
      effects: effects,
      timestamp: Date.now()
    }
    
    this.combinationHistory.push(combination)
    
    // 保存到本地存储
    this.saveCombinationHistory()
    
    console.log('Combination recorded:', combination)
  }
  
  // 计算组合效果
  calculateCombinationEffects(card1, card2) {
    const effects = []
    
    // 应用所有匹配的规则
    this.combinationRules.forEach(rule => {
      if (rule.matches(card1, card2)) {
        const result = rule.apply(card1, card2)
        effects.push({
          id: rule.id,
          name: rule.name,
          icon: rule.icon,
          description: result.description,
          result: result
        })
      }
    })
    
    return effects
  }
  
  // 检查组合可能性
  canCombine(card1, card2) {
    return this.combinationRules.some(rule => rule.matches(card1, card2))
  }
  
  // 获取组合建议
  getCombinationSuggestions(card) {
    const suggestions = []
    
    // 基于卡牌属性生成建议
    if (card.attributes) {
      Object.keys(card.attributes).forEach(attribute => {
        suggestions.push({
          type: 'attribute_match',
          description: `寻找具有 ${attribute} 属性的卡牌`,
          priority: 'high'
        })
      })
    }
    
    // 基于信任值生成建议
    if (card.trustValue < 50) {
      suggestions.push({
        type: 'trust_boost',
        description: '寻找高信任值卡牌进行组合',
        priority: 'medium'
      })
    }
    
    // 基于历史组合生成建议
    const historySuggestions = this.getHistoryBasedSuggestions(card)
    suggestions.push(...historySuggestions)
    
    return suggestions
  }
  
  // 基于历史生成建议
  getHistoryBasedSuggestions(card) {
    const suggestions = []
    const cardHistory = this.combinationHistory.filter(combo => 
      combo.card1Id === card.id || combo.card2Id === card.id
    )
    
    if (cardHistory.length > 0) {
      // 分析成功的组合模式
      const successfulCombos = cardHistory.filter(combo => combo.effects.length > 0)
      
      if (successfulCombos.length > 0) {
        suggestions.push({
          type: 'historical_success',
          description: '基于历史成功组合寻找相似卡牌',
          priority: 'high'
        })
      }
    }
    
    return suggestions
  }
  
  // 获取拖拽统计
  getDragStatistics() {
    const totalDrags = this.dragHistory.length
    const successfulDrags = this.dragHistory.filter(drag => drag.success).length
    const averageDuration = this.dragHistory.reduce((sum, drag) => sum + (drag.duration || 0), 0) / totalDrags
    
    const totalCombinations = this.combinationHistory.length
    const successfulCombinations = this.combinationHistory.filter(combo => combo.effects.length > 0).length
    
    return {
      totalDrags: totalDrags,
      successfulDrags: successfulDrags,
      successRate: totalDrags > 0 ? (successfulDrags / totalDrags) * 100 : 0,
      averageDuration: averageDuration,
      totalCombinations: totalCombinations,
      successfulCombinations: successfulCombinations,
      combinationSuccessRate: totalCombinations > 0 ? (successfulCombinations / totalCombinations) * 100 : 0
    }
  }
  
  // 获取组合历史
  getCombinationHistory(limit = 10) {
    return this.combinationHistory
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(0, limit)
  }
  
  // 获取最常用组合
  getMostUsedCombinations(limit = 5) {
    const combinationCounts = new Map()
    
    this.combinationHistory.forEach(combo => {
      const key = `${combo.card1Id}-${combo.card2Id}`
      combinationCounts.set(key, (combinationCounts.get(key) || 0) + 1)
    })
    
    return Array.from(combinationCounts.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, limit)
      .map(([key, count]) => {
        const [card1Id, card2Id] = key.split('-')
        return {
          card1Id: card1Id,
          card2Id: card2Id,
          count: count
        }
      })
  }
  
  // 注册拖拽区域
  registerDropZone(zoneId, element) {
    this.dropZones.set(zoneId, {
      element: element,
      registeredAt: Date.now()
    })
  }
  
  // 注销拖拽区域
  unregisterDropZone(zoneId) {
    this.dropZones.delete(zoneId)
  }
  
  // 获取活跃拖拽
  getActiveDrags() {
    return Array.from(this.activeDrags.values())
  }
  
  // 清理过期拖拽
  cleanupExpiredDrags() {
    const now = Date.now()
    const expiredTime = 5 * 60 * 1000 // 5分钟
    
    this.activeDrags.forEach((drag, cardId) => {
      if (now - drag.startTime > expiredTime) {
        this.activeDrags.delete(cardId)
      }
    })
  }
  
  // 保存组合历史
  saveCombinationHistory() {
    try {
      const data = {
        combinationHistory: this.combinationHistory,
        lastUpdate: Date.now()
      }
      uni.setStorageSync('trustDragHistory', JSON.stringify(data))
      return true
    } catch (error) {
      console.error('Failed to save combination history:', error)
      return false
    }
  }
  
  // 加载组合历史
  loadCombinationHistory() {
    try {
      const data = uni.getStorageSync('trustDragHistory')
      if (data) {
        const parsedData = JSON.parse(data)
        this.combinationHistory = parsedData.combinationHistory || []
        return true
      }
    } catch (error) {
      console.error('Failed to load combination history:', error)
    }
    return false
  }
  
  // 清除所有数据
  clearAllData() {
    this.dragHistory = []
    this.combinationHistory = []
    this.activeDrags.clear()
    this.dropZones.clear()
    
    try {
      uni.removeStorageSync('trustDragHistory')
      return true
    } catch (error) {
      console.error('Failed to clear data:', error)
      return false
    }
  }
  
  // 导出数据
  exportData() {
    return {
      dragHistory: this.dragHistory,
      combinationHistory: this.combinationHistory,
      statistics: this.getDragStatistics(),
      exportTime: Date.now()
    }
  }
  
  // 导入数据
  importData(data) {
    try {
      if (data.dragHistory) {
        this.dragHistory = data.dragHistory
      }
      if (data.combinationHistory) {
        this.combinationHistory = data.combinationHistory
      }
      return true
    } catch (error) {
      console.error('Failed to import data:', error)
      return false
    }
  }
}

export default new TrustDragManager()

